package org.vectrics.recruiter.struts.tag;

/**
 * @author Mike Moore
 */

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.html.A;
import org.apache.ecs.html.Input;
import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Form;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.TextHelper;
import org.vectrics.common.pagelist.PageList;
import org.vectrics.common.util.StringUtils;
import org.vectrics.common.view.FieldTable;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.document.CandidateDocument;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobCandidate;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.recruiter.user.ResumeScanBatch;
import org.vectrics.recruiter.user.ResumeScanCriteria;
import org.vectrics.recruiter.user.ResumeScanResult;
import org.vectrics.struts.PageListTag;
import org.vectrics.user.Person;


public class ResumeScanResultTag extends PageListTag {

	private static final long serialVersionUID = 4633533165173777108L;
	
	static private transient Logger log = Logger.getLogger(ResumeScanResultTag.class);
    public static String PREV_JOB_PARAM = "prev_job";
    public static String NEXT_JOB_PARAM = "next_job";
    private String batchId = null;
    private String jobId = null;
    private ResumeScanBatch batch = null;
 
    public String getNoElementsMessage() {
        return(null);
    }
    
    private ResumeScanBatch getBatch() {
   		batch = RecruitServiceLocator.getRecruitUserService().findResumeScanBatch(new Long(batchId));
    	return(batch);
    }
    
    protected Form createForm(String actionForm) {
    	Form form = new Form();
    	form.setAction(actionForm);
    	Input batchHidden = form.addHidden();
    	batchHidden.setName("batchId");
    	batchHidden.setValue(batchId);
    	
    	if (this.getJob() != null) {
    		Input jobHidden = form.addHidden();
    		jobHidden.setName("jobId");
    		jobHidden.setValue(this.getJobId());
    	}
    	return(form);
    }
    
    public PageList createPageList() {
        ResumeScanPageList pageList = new ResumeScanPageList(new Long(batchId));
        return(pageList);
    }
    
    private Job getJob() {
    	Job job = null;
    	if (StringUtils.isNullOrBlank(this.getJobId()) == false) {
    		job = RecruitServiceLocator.getJobProvider().findJob(new Long(this.getJobId()));
    	}
    	return(job);
    }
    
    protected String getTopOfPageContent() {
    	StringBuffer html = new StringBuffer();
    	
    	ResumeScanBatch batch = this.getBatch();
        FieldTable table = new FieldTable();
        table.setCellPadding(2);
        table.setWidth(500);
        table.setValueCellWidth("350");
        table.showField(this.getPhrase("prompt.resume.batch.description"), batch.getDescription());
        

        Iterator iter = batch.getCriteriaList().iterator();
        while (iter.hasNext()) {
        	ResumeScanCriteria criteria = (ResumeScanCriteria)iter.next();
        	String criteriaSummary = "Phrase = \"" + criteria.getPhrase() +
			     "\"     Weight = " + criteria.getWeight();
            table.showField(this.getPhrase("prompt.resume.batch.criteria"), criteriaSummary);
        }
        Job job = this.getJob();
        if (job != null)
        	table.showField(this.getPhrase("prompt.job.info"), job.getReferenceId() + " - " + job.getTitle());
        
        html.append(table.toString());
    	return(html.toString());
    }
    
    /**
     * @return Returns the batchId.
     */
    public String getBatchId() {
        return batchId;
    }
    /**
     * @param batchId The batchId to set.
     */
    public void setBatchId(String batchId) {
        this.batchId = batchId;
    }
    
    public String getJobId() {
		return jobId;
	}

	public void setJobId(String jobId) {
		this.jobId = jobId;
	}

	public String getDescription() {
        return(null);
    }
    
    public String getPageListLink() {
		String href = this.getContextPath() + "/admin/jobs/resumeScanResults.do" 
			+ "?batchId=" + batchId;
        return(href);
    }
    
    public void showList(String header, Cell mainCell, List resumeResults, Form form) {
		log.info("doStartTag() called");
    	HttpServletRequest request = (HttpServletRequest)super.pageContext.getRequest();
        
        
        request.removeAttribute("resumeScores");
        BorderTable table = new BorderTable();
        mainCell.addElement(table);
        table.setWidth(600);
        Row hdrRow = table.addRow();
        hdrRow.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");
        Cell hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Score"));
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        hdrCell.addElement(TextHelper.getFont("tableHdrFont", "User"));
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Resume Name"));
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Resume Date"));
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Resume Type"));
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");
        
        hdrCell = hdrRow.addCell();
        //hdrCell.setClass("tableHdrBg");

        Job job = this.getJob();
    	if (job != null) {
            hdrCell = hdrRow.addCell();
            hdrCell.addText("tableHdrFont", this.getPhrase("prompt.resume.scan.job.make.candidate"));
           // hdrCell.setClass("tableHdrBg");
    	}
    		
        Iterator iter = resumeResults.iterator();
        while (iter.hasNext()) {
            ResumeScanResult result = (ResumeScanResult)iter.next();
        	try {
	        	CandidateDocument candidateDocument = result.getDocument();
	        	Person person = result.getPerson();
	        	Row row = table.addRow();
	        	Cell cell = row.addCell();
	        	cell.addElement(TextHelper.getFont("subFont", "" + result.getScore()));
	        	
	        	cell = row.addCell();
	        	cell.addElement(TextHelper.getFont("subFont", person.getName()));
	        	
	        	cell = row.addCell();
	        	cell.addElement(TextHelper.getFont("subFont", candidateDocument.getName()));
	        	
	        	cell = row.addCell();
	        	cell.addElement(TextHelper.getFont("subFont", CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(this.getLocale()).format(candidateDocument.getLastUpdate())));
	        	
	        	cell = row.addCell();
        		if (candidateDocument.getSavedFileName().toLowerCase().endsWith(".doc")) {
        			cell.addElement(TextHelper.getFont("subFont", "MS Word"));
        		}
        		else if (candidateDocument.getSavedFileName().toLowerCase().endsWith(".txt")) {
        			cell.addElement(TextHelper.getFont("subFont", "Text"));
        		}
        		else if (candidateDocument.getSavedFileName().toLowerCase().endsWith(".pdf")) {
        			cell.addElement(TextHelper.getFont("subFont", "PDF"));
        		}
        		else {
        			cell.addElement(TextHelper.getFont("subFont", "Unknown Format"));
	        	}
	        	
	        	cell = row.addCell();
        		A userLink = new A();
        		userLink.setClass("subLink");
        		userLink.setHref(request.getContextPath() + "/admin/user/view.do?userId=" + person.getId());
        		userLink.setOnClick("OpenLarge(this.href, '" + person.getId() + "'); return false");
        		userLink.addElement("view candidate");
        		cell.addElement(userLink);
	        	
        		
	        	cell = row.addCell();
	        	A retrieveLink = new A();
	        	retrieveLink.setClass("subLink");
	        	retrieveLink.setHref(request.getContextPath() + "/retrievedocument/resume/" + candidateDocument.getSavedFileName()
	        			+ "?documentId=" + candidateDocument.getId());
	        	retrieveLink.setOnClick("OpenLarge(this.href, '" + candidateDocument.getId() + "'); return false");
	        	retrieveLink.addElement("retrieve");
	        	cell.addElement(retrieveLink);
        		
	        	boolean isCurrentCandidate = false;
	        	if (job != null) {
		        	cell = row.addCell();
	        		CandidateInfo candidateInfo = RecruitServiceLocator.getRecruitUserService()
	        				.findCandidateInfo(person);
	        		if (candidateInfo != null) {
	        			job = RecruitServiceLocator.getJobProvider().findJob(job.getId());
		        		JobCandidate jobCandidate = job.findJobCandidate(candidateInfo);
			        	if (jobCandidate != null) {
		        			isCurrentCandidate = true;
		        			log.debug("Show candidate status for person, no changes allowed.");
		        			cell.addText("subFont", jobCandidate.getCurrentStatus().getStatusType().getDescription());
			        	}
	        		}
	        		
	        		if (isCurrentCandidate == false) {
		        		A newCandidateLink = new A();
		        		newCandidateLink.setHref(this.getRequest().getContextPath() 
		        				+ "/admin/jobs/candidate/add.do?jobId=" + job.getId().toString()
		        				+ "&userId=" + person.getId().toString());
			        	newCandidateLink.setOnClick("OpenLargeWithRefresh(this.href, '1'); return false");
		        		newCandidateLink.setClass("subFont");
		        		newCandidateLink.addElement(this.getPhrase("phrase.make.candidate.for.job"));
		        		cell.addElement(newCandidateLink);
	        		}
	        	}
        	} catch (Exception de) {
        		log.error("Exception finding or displaying data", de);
        		throw new SystemException("Exception finding or displaying data", de);
        	}
        }
    }

    
    private String getJobCheckBoxName(Job job, Person person) {
    	String name = "chk_" + job.getId().toString() + "_" + person.getId().toString();
    	return(name);
    }
    
    @Override
    protected String getFormAction() {
    	return this.getContextPath() + "/admin/jobs/resumeScanResults.do";
    }
    
}
